package com.iemes.service.impl.work_process;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.ibatis.builder.BuilderException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.FlowStepFormMap;
import com.iemes.entity.NcRepairFormMap;
import com.iemes.entity.SfcAssemblyFormMap;
import com.iemes.entity.SfcNcFormMap;
import com.iemes.entity.SfcStepFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.WorkResourceFormMap;
import com.iemes.entity.WorkShopInventoryFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.mapper.workProcess.WorkPodPanelMapper;
import com.iemes.service.CommonService;
import com.iemes.service.work_process.WorkPodPanelService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONObject;

@Service
public class WorkPodPanelServiceImpl implements WorkPodPanelService {

	private Logger log = Logger.getLogger(WorkPodPanelServiceImpl.class);

	@Inject
	private WorkPodPanelMapper workPodPanelMapper;
	
	@Inject
	protected BaseMapper baseMapper;
	
	@Inject
	private CommonService commonService;

	@Override
	public List<Map<String, String>> getSfcOnOperation(String operationId) throws BusinessException {
		return workPodPanelMapper.getSfcOnOperation(operationId);
	}

	@Override
	public List<SfcStepFormMap> getSfcWaitOnOperation(String operationId, String workResourceId, String sfc)
			throws BusinessException {
		return workPodPanelMapper.getSfcWaitOnOperation(operationId, workResourceId, sfc);
	}

	@Override
	public List<Map<String, String>> getButtonsByPodPanel(String podPanelId) throws BusinessException {
		return workPodPanelMapper.getButtonsByPodPanel(podPanelId);
	}

	@Override
	@Transactional
	public void editFormMap(Object formMap) throws BusinessException {
		try {
			workPodPanelMapper.editEntity(formMap);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}
	

	@Override
	@Transactional
	public void podStart(SfcStepFormMap sfcStepFormMap, SfcStepFormMap sfcStepFormMap2, ShopOrderSfcFormMap shopOrderSfcFormMap)
			throws BuilderException {
		try {
			workPodPanelMapper.editEntity(sfcStepFormMap);
			workPodPanelMapper.addEntity(sfcStepFormMap2);
			if (shopOrderSfcFormMap!=null) {
				workPodPanelMapper.editEntity(shopOrderSfcFormMap);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	@Transactional
	public void podFinish(JSONObject data, String next_operation_id) throws BusinessException {
		try {
			String id = data.getString("id");
			if (StringUtils.isEmpty(next_operation_id)) {
				//最后一步
				
				//1.1 追加sfc_step表上一步完成时间
				List<SfcStepFormMap> listSfcStepFormMap = workPodPanelMapper.findByAttribute("id", id, SfcStepFormMap.class);
				SfcStepFormMap sfcStepFormMap = listSfcStepFormMap.get(0);
				sfcStepFormMap.put("finish_time", DateUtils.getStringDateTime());
				workPodPanelMapper.editEntity(sfcStepFormMap);
				
				//1.2 添加一条与上一条相同，但状态为已完成的记录
				SfcStepFormMap sfcStepFormMap3 = new SfcStepFormMap();
				sfcStepFormMap3.putAll(sfcStepFormMap);
				sfcStepFormMap3.remove("seq");
				sfcStepFormMap3.put("id", UUIDUtils.getUUID());
				sfcStepFormMap3.put("status", 2);
				sfcStepFormMap3.put("create_user", ShiroSecurityHelper.getCurrentUsername());
				sfcStepFormMap3.put("create_time", DateUtils.getStringDateTime());
				workPodPanelMapper.addEntity(sfcStepFormMap3);
				
				//1.3 修改shoporder_sfc表状态为2（已完成）
				ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
				shopOrderSfcFormMap.put("shoporder_id", sfcStepFormMap.getStr("shoporder_id"));
				shopOrderSfcFormMap.put("sfc", sfcStepFormMap.getStr("sfc"));
				shopOrderSfcFormMap.put("workshop_id", sfcStepFormMap.getStr("workshop_id"));
				shopOrderSfcFormMap.put("workline_id", sfcStepFormMap.getStr("workline_id"));
				shopOrderSfcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
				List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = workPodPanelMapper.findByNames(shopOrderSfcFormMap);
				ShopOrderSfcFormMap shopOrderSfcFormMap2 = listShopOrderSfcFormMap.get(0);
				shopOrderSfcFormMap2.put("sfc_finish_time", DateUtils.getStringDateTime());
				shopOrderSfcFormMap2.put("sfc_status", 2);
				workPodPanelMapper.editEntity(shopOrderSfcFormMap2);
				
				//1.4 判断是否为工单的最后一个，是则修改工单状态为已完成
				
				ShoporderFormMap shoporderFormMap = commonService.isLastSfcOnShoporder(sfcStepFormMap.getStr("shoporder_id"));
				if (shoporderFormMap!=null) {
					shoporderFormMap.put("status", 3);
					workPodPanelMapper.editEntity(shoporderFormMap);
				}
			}else {
				//1.1 追加sfc_step表上一步完成时间
				List<SfcStepFormMap> listSfcStepFormMap = workPodPanelMapper.findByAttribute("id", id, SfcStepFormMap.class);
				SfcStepFormMap sfcStepFormMap = listSfcStepFormMap.get(0);
				sfcStepFormMap.put("finish_time", DateUtils.getStringDateTime());
				workPodPanelMapper.editEntity(sfcStepFormMap);
				
				//1.2 添加一条与上一条相同，但状态为已完成的记录
				SfcStepFormMap sfcStepFormMap3 = new SfcStepFormMap();
				sfcStepFormMap3.putAll(sfcStepFormMap);
				sfcStepFormMap3.put("id", UUIDUtils.getUUID());
				sfcStepFormMap3.put("status", 2);
				sfcStepFormMap3.put("create_user", ShiroSecurityHelper.getCurrentUsername());
				sfcStepFormMap3.put("create_time", DateUtils.getStringDateTime());
				workPodPanelMapper.addEntity(sfcStepFormMap3);
				
				//1.2 新增一条sfc_step记录，状态为0
				SfcStepFormMap sfcStepFormMap2 = new SfcStepFormMap();
				sfcStepFormMap2.put("id", UUIDUtils.getUUID());
				sfcStepFormMap2.put("sfc", data.getString("sfc"));
				sfcStepFormMap2.put("process_workflow_id", data.getString("process_workflow_id"));
				sfcStepFormMap2.put("operation_id", next_operation_id);
				sfcStepFormMap2.put("status", 0);
				sfcStepFormMap2.put("create_user", ShiroSecurityHelper.getCurrentUsername());
				sfcStepFormMap2.put("create_time", DateUtils.getStringDateTime());
				sfcStepFormMap2.put("workline_id", data.getString("workline_id"));
				sfcStepFormMap2.put("shoporder_id", data.getString("shoporder_id"));
				sfcStepFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
				sfcStepFormMap2.put("item_id", data.getString("item_id"));
				sfcStepFormMap2.put("shift_id", data.getString("shift_id"));
				sfcStepFormMap2.put("workshop_id", data.getString("workshop_id"));
				sfcStepFormMap2.put("shoporder_sfc_id", data.getString("shoporder_sfc_id"));
				workPodPanelMapper.addEntity(sfcStepFormMap2);
			}
		}catch(Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}
	
	@Override
	@Transactional
	public void podBindShoporder(String bindSfc,ShoporderFormMap bindSoporderFormMap, 
			FlowStepFormMap bindFistFlowStepFormMap,WorkResourceFormMap bindWorkResourceFormMap)
			throws BusinessException {
		try {
			String shoporderId = bindSoporderFormMap.getStr("id");
			String siteId = ShiroSecurityHelper.getSiteId();
			String workshopId = bindWorkResourceFormMap.getStr("workshop_id");
			String worklineId = bindWorkResourceFormMap.getStr("workline_id");
			String workflowId = bindFistFlowStepFormMap.getStr("process_workflow_id");
			String firstOperationId = bindFistFlowStepFormMap.getStr("operation_id");
			String itemId =  bindSoporderFormMap.getStr("shoporder_item_id");
			// 1.向mds_shoporder_sfc表插入sfc信息
			ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
			String sfcId = UUIDUtils.getUUID();
			shopOrderSfcFormMap.put("id", sfcId);
			shopOrderSfcFormMap.put("shoporder_id", shoporderId);
			shopOrderSfcFormMap.put("sfc", bindSfc);
			shopOrderSfcFormMap.put("sfc_status", 0);
			shopOrderSfcFormMap.put("site_id", siteId);
			shopOrderSfcFormMap.put("workshop_id", workshopId);
			shopOrderSfcFormMap.put("workline_id", worklineId);
			shopOrderSfcFormMap.put("is_printed", -1);
			shopOrderSfcFormMap.put("create_time", DateUtils.getStringDateTime());
			shopOrderSfcFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());

			baseMapper.addEntity(shopOrderSfcFormMap);

			// 2.向mds_sfc_step表插入对应工艺路线的首操作，且状态为创建的记录。
			SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
			sfcStepFormMap.put("id", UUIDUtils.getUUID());
			sfcStepFormMap.put("sfc", bindSfc);
			sfcStepFormMap.put("shoporder_sfc_id", sfcId);
			sfcStepFormMap.put("process_workflow_id", workflowId);
			sfcStepFormMap.put("operation_id", firstOperationId);
			sfcStepFormMap.put("status", 0);
			sfcStepFormMap.put("workline_id", worklineId);
			sfcStepFormMap.put("shoporder_id", shoporderId);
			sfcStepFormMap.put("site_id", siteId);
			sfcStepFormMap.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			
			//增加 work_resource_id item_id shift_id workshop_id
			
			sfcStepFormMap.put("item_id", itemId);
			sfcStepFormMap.put("workshop_id", workshopId);

			baseMapper.addEntity(sfcStepFormMap);
			
		}catch(Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	public List<Map<String, Object>> getAssembleList(Map<String, String> map) throws BusinessException {
		return workPodPanelMapper.getAssembleList(map);
	}

	@Override
	@Transactional
	public void assembleItem(SfcAssemblyFormMap sfcAssemblyFormMap) throws BusinessException {
		try {
			String item_sfc = sfcAssemblyFormMap.getStr("item_sfc");
			String item_id = sfcAssemblyFormMap.getStr("item_id");
			String sfc = sfcAssemblyFormMap.getStr("sfc");
			String item_inner_batch = sfcAssemblyFormMap.getStr("item_inner_batch");
			String item_save_type = sfcAssemblyFormMap.getStr("item_save_type");
			String use_num = sfcAssemblyFormMap.getStr("use_num");
			String item_name = sfcAssemblyFormMap.getStr("item_name");
			
			SfcAssemblyFormMap sfcAssemblyFormMap3 = new SfcAssemblyFormMap();
			sfcAssemblyFormMap3.put("item_id", item_id);
			if ("batch".equals(item_save_type)) {
				sfcAssemblyFormMap3.put("item_inner_batch", item_inner_batch);
			}else if ("unit".equals(item_save_type)){
				sfcAssemblyFormMap3.put("sfc", sfc);
			}
			
			sfcAssemblyFormMap3.put("site_id", ShiroSecurityHelper.getSiteId());
			List<SfcAssemblyFormMap> list2 = workPodPanelMapper.findByNames(sfcAssemblyFormMap3);
			
			if (ListUtils.isNotNull(list2)) {
				int useNum = 0;
				for (SfcAssemblyFormMap sfcAssemblyFormMap2 : list2) {
					int use_number = sfcAssemblyFormMap2.getInt("use_number");
					useNum = useNum + use_number;
				}
				if (useNum>=Integer.parseInt(use_num)) {
					String msg = "物料：["+item_name+"] 已装配完成，无需再次装配";
					log.error(msg);
					throw new BusinessException(msg);
				}
			}
			
			if ("unit".equals(item_save_type)) {
				for (SfcAssemblyFormMap sfcAssemblyFormMap2 : list2) {
					String item_sfc2 = sfcAssemblyFormMap2.getStr("item_sfc");
					if (item_sfc2.equals(item_sfc)) {
						String msg = "组件：["+item_sfc+"] 已装配，不允许重复装配";
						log.error(msg);
						throw new BusinessException(msg);
					}
				}
			}else if ("batch".equals(item_save_type)) {
				Map<String,String> param = new HashMap<String, String>();
				param.put("site_id", ShiroSecurityHelper.getSiteId());
				param.put("item_inner_batch", item_inner_batch);
				int remanent_num = workPodPanelMapper.getValidItemBatchNum(param);
				String use_number = sfcAssemblyFormMap.getStr("use_number");
				if (Integer.parseInt(use_number)>remanent_num) {
					String msg = "装配数量不能超过剩余数量，剩余数量为："+remanent_num;
					log.error(msg);
					throw new BusinessException(msg);
				}
			}
			sfcAssemblyFormMap.put("item_sfc", item_sfc);
			sfcAssemblyFormMap.put("id", UUIDUtils.getUUID());
			sfcAssemblyFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcAssemblyFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcAssemblyFormMap.put("create_time", DateUtils.getStringDateTime());
			workPodPanelMapper.addEntity(sfcAssemblyFormMap);
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			throw new BusinessException(msg);
		}
	}

	/**
	 * 记录不良
	 * @param sfcNcFormMap	不良表插入记录
	 * @param sfcStepFormMap	追加当前步骤的完成时间
	 * @param sfcStepFormMap2	添加一条当前步骤完成记录
	 * @param sfcStepFormMap3	添加下一条维修操作记录
	 * @param ShopOrderSfcFormMap	修改sfc状态为维修中
	 * @throws BusinessException
	 */
	@Override
	@Transactional
	public void recordNcCode(SfcNcFormMap sfcNcFormMap, SfcStepFormMap sfcStepFormMap, 
			SfcStepFormMap sfcStepFormMap2, SfcStepFormMap sfcStepFormMap3, ShopOrderSfcFormMap shopOrderSfcFormMap) throws BusinessException {
		try {
			sfcNcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcNcFormMap.put("status", -1);
			sfcNcFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcNcFormMap.put("create_time", DateUtils.getStringDateTime());
			workPodPanelMapper.addEntity(sfcNcFormMap);
			workPodPanelMapper.editEntity(sfcStepFormMap);
			workPodPanelMapper.addEntity(sfcStepFormMap2);
			workPodPanelMapper.addEntity(sfcStepFormMap3);
			workPodPanelMapper.editEntity(shopOrderSfcFormMap);
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			throw new BusinessException(msg);
		}
	}

	@Override
	@Transactional
	public void podScrap(SfcNcFormMap sfcNcFormMap, NcRepairFormMap ncRepairFormMap, SfcStepFormMap lastSfcStep, 
			SfcStepFormMap sfcStepFormMap, ShopOrderSfcFormMap shopOrderSfcFormMap, ShoporderFormMap lastSfcOnShoporder) throws BusinessException {
		try {
			workPodPanelMapper.editEntity(sfcNcFormMap);
			workPodPanelMapper.addEntity(ncRepairFormMap);
			workPodPanelMapper.editEntity(lastSfcStep);
			workPodPanelMapper.addEntity(sfcStepFormMap);
			workPodPanelMapper.editEntity(shopOrderSfcFormMap);
			if (lastSfcOnShoporder!=null) {
				lastSfcOnShoporder.put("status", 3);
				workPodPanelMapper.editEntity(lastSfcOnShoporder);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			throw new BusinessException(msg);
		}
	}

	@Override
	@Transactional
	public void podRepair(SfcNcFormMap sfcNcFormMap, NcRepairFormMap ncRepairFormMap, SfcStepFormMap lastSfcStep,
			SfcStepFormMap sfcStepFormMap, SfcStepFormMap sfcStepFormMap2) throws BusinessException {
		try {
			workPodPanelMapper.editEntity(sfcNcFormMap);
			workPodPanelMapper.addEntity(ncRepairFormMap);
			workPodPanelMapper.editEntity(lastSfcStep);
			workPodPanelMapper.addEntity(sfcStepFormMap);
			workPodPanelMapper.addEntity(sfcStepFormMap2);
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			throw new BusinessException(msg);
		}
	}

	@Override
	public List<WorkShopInventoryFormMap> getValidItemBatch(Map<String, String> param) {
		return workPodPanelMapper.getValidItemBatch(param);
	}

}
